
/*
 * ====================================================
 * 投票调查
 */
$(function(){
	$(".minBtn").click(function(){
		$("#toggle_1").slideToggle(600);
	});
});

var VoteSurvey = {};
//投票调查相关全局属性
var VS_ATTR = {
		zIndex:2000//全屏时z-index是1000，所以这里的值要大于1000.
	};

function loadVoteAndSurveys(obj){
	info(">> [loadVoteAndSurveys] original data:",obj);
	if(!obj || !obj.contentArray || obj.contentArray.length==0)return;
	for(var i in obj.contentArray){
		loadVoteAndSurvey(obj.contentArray[i]);
	}
}

function loadVoteAndSurvey(data){
	info(">> [loadVoteAndSurvey] vote and survey:", data);
	if(isQuestion(data)){
		popupVoteAndSurvey(data);
	}else if(data.rootType ==="result"){
		popupVoteAndSurveyResult(data);
	}else{
		error("[ipad-live.vote][loadVoteAndSurvey] data unknown:", data);
		return;
	}
	
	$("#minItemContainer").show();
	appendMinimizeItem(data);
}

function popupVoteAndSurvey(vsData){
	VoteSurvey[vsData.id] = vsData;
	var questions = vsData.question;
	var sElem = '<div class="vote" id="vs_'+ vsData.id+'">' 
						+'<div class="title">'
					+'<h3 class="titleR">'
						+'<p class="titleM">'+iPadLang.voteAndSurvey+'<a href=\'javascript:minimize("vs_'+vsData.id+'");\' class="votemin';
	if(vsData.skip=="false"){
		sElem +=		  ' showAfter';
	}
			sElem +=	'">&mdash;</a>'
						+' <a href=\'javascript:close("vs_'+vsData.id+'");\' class="voteclose';
	if(vsData.skip=="false"){
		sElem +=		  ' showAfter';
	}
	sElem +=				'">X</a></p>'
					+'</h3>'
				+'</div>'
				+'<div class="voteCnt">'
					+'<div class="voteCntR">'
						+'<div class="voteCntM">';
	for(var i in questions){
		var question = questions[i];
		if(question.type=="single" || question.type=="multi"){
			sElem += createVote(i, question);
		}else if(question.type=="text"){
			sElem += createSurvey(i, question);
		}else{
			error("[ipad-live.vote][popupVoteAndSurvey] type of VoteAndSurvey is error:", question.type);
		}
	}
	sElem += 			'<div class="votebtn">'
							+'<input type="button" value="'+iPadLang.submitBtn+'" class="tpbtn">'
						+'</div>'
					+'</div>'
				+'</div>'
			+'</div>'
		+'<div class="voteBtm">'
			+'<div class="voteBtmR">'
			+	'<p class="voteBtmM"></p>'
			+'</div>'
		+'</div>';
	$(sElem).appendTo("#voteContainer");
	$("#vs_"+ vsData.id).find(".tpbtn").bind("click", function(){commitVoteAndSurvey(vsData.id);});
	$("#vs_"+ vsData.id).bind("click",function(){focus("vs_"+ vsData.id);});
	focus("vs_"+ vsData.id);
}

function commitVoteAndSurvey(vsDataId){
	debug("[ipad-live.vote][commitVoteAndSurvey] start:", vsDataId);
	var vsData = VoteSurvey[vsDataId];
	if(vsData.skip=="false"){
		if(!isAllQuestionAnswered(vsData)){
			alert(iPadLang.answerAllTip);
			return false;
		}
	}else{
		if(!isOneAnsweredAtLeast(vsData)){
			alert(iPadLang.answerOneAtLeastTip);
			return false;
		}
	}
	
	$("#vs_"+ vsDataId).find(".tpbtn").unbind("click");
	$("#vs_"+ vsDataId).find(".tpbtn").val(iPadLang.submittingBtn);
	
	$("#vs_"+vsDataId).find(".question").each(function(){
		if($(this).hasClass("toupiao")){
			var answer = "";
			$(this).find(":radio").each(function(){
				if($(this).attr("checked")=="checked"){
					debug("radio checked:", $(this).val());
					
					if(answer.length==0){
						answer = $(this).val();
					}else{
						answer += ","+ $(this).val();
					}
				}
				$(this).attr("disabled", "disabled");
			});
			$(this).find(":checkbox").each(function(){
				if($(this).attr("checked")=="checked"){
					debug("checkbox checked:", $(this).val());
					
					if(answer.length==0){
						answer = $(this).val();
					}else{
						answer += ","+ $(this).val();
					}
				}
				$(this).attr("disabled", "disabled");
			});
			
			setAnswer(vsData, $(this).attr("id"), answer);
		}else if($(this).hasClass("diaocha")){
			var testarea = $(this).find("textarea");
			var answer = testarea.val();
			setAnswer(vsData, $(this).attr("id"), answer);
			testarea.attr("disabled", "disabled");
		}else{
			error("[ipad-live.vote][commitVoteAndSurvey] not has class toupiao or diaocha:", this );
		}

		var $span = $(this).find(".correctFlag");
		$span.parent().addClass("rightans");
		
	});
	
	$("#vs_"+ vsDataId).find(".tpbtn").val(iPadLang.submittedBtn);
	$("#vs_"+ vsDataId).find(".showAfter").removeClass("showAfter");
	info("<< submit vote and survey：", VoteSurvey[vsDataId]);
	submitVoteAndSurvey([VoteSurvey[vsDataId]]);
	delete VoteSurvey[vsDataId];
}

function isAllQuestionAnswered(vsData){
	var allAnswered = true;
	$("#vs_"+vsData.id).find(".question").each(function(){
		var answered = true;
		if($(this).hasClass("toupiao")){
			$(this).find(":radio").each(function(){
				answered = false;
				if($(this).attr("checked")=="checked"){
					answered = true;
					return false;
				}
			});
			$(this).find(":checkbox").each(function(){
				answered = false;
				if($(this).attr("checked")=="checked"){
					answered = true;
					return false;
				}
			});
			
		}else if($(this).hasClass("diaocha")){
			var val = $(this).find("textarea").val();
			if(!val||$.trim(val).length<1){
				answered = false;
			}
		}
		if(!answered){
			allAnswered = false;
			return false;
		}
	});
	return allAnswered;
}

function isOneAnsweredAtLeast(vsData){
	var oneAnswered = false;
	$("#vs_"+vsData.id).find(".question").each(function(){
		if($(this).hasClass("toupiao")){
			$(this).find(":radio").each(function(){
				if($(this).attr("checked")=="checked"){
					oneAnswered = true;
					return false;
				}
			});
			$(this).find(":checkbox").each(function(){
				if($(this).attr("checked")=="checked"){
					oneAnswered = true;
					return false;
				}
			});
			
		}else if($(this).hasClass("diaocha")){
			var val = $(this).find("textarea").val();
			if(val&&$.trim(val).length>0){
				oneAnswered = true;
			}
		}
		if(oneAnswered){
			return false;
		}
	});
	return oneAnswered;
}

function setAnswer(vsData, itemId, value){
	info("[ipad-live.vote][setAnswer] id:"+vsData.id+", itemId:"+itemId+", answer:"+value);
	var questions = vsData.question;
	for(var i in questions){
		if(questions[i].id===itemId){
			questions[i].answer = value;
			break;
		}
	}
}

function createVote(idx, voteData){
	
	var sVoteElem = '<div class="toupiao question" id="'+voteData.id+'">'+
					'<h3>'+voteData.subject+'</h3>'+
					'<div class="toupiaoCnt">';
	for(var i in voteData.items){
		var item = voteData.items[i];
		sVoteElem += '<label>'; //class="rightans"
		if(voteData.type==="single"){
			sVoteElem += '<input type="radio" value="'+(Number(i)+1)+'" name="radio'+idx+'"> '+item.content;
		}else{
			sVoteElem += '<input type="checkbox" value="'+(Number(i)+1)+'"> '+item.content;
		}
		if(isCorrectItem(item)){
			sVoteElem += '<span class="correctFlag showAfter"> - '+iPadLang.correctAnswer+'</span>';
		}
		sVoteElem +=  '</label><br>';
	}
	sVoteElem +=  '</div>'+
				'</div>';
	return sVoteElem;
}

function isCorrectItem(item){
	return item.correct =="true" || item.correct == true;
}


function createSurvey(idx, surveyData){
	var sSurveyElem = '<div class="diaocha question" id="'+surveyData.id+'">' +
						'<h3>'+surveyData.subject+'</h3>'+
						'<div class="diaochaCnt">'+
							'<textarea rows="" cols="" name="" class="txt"></textarea>'+
						'</div>'+
					'</div>';
	return sSurveyElem;
}

function popupVoteAndSurveyResult(vsrData){
	var questions = vsrData.question;
	var sElem = '<div class="voteResult" id="vsr_'+vsrData.id+'">'+
	'<div class="title">'+
		'<h3 class="titleR">'+
			'<p class="titleM">'+iPadLang.voteAndSurveyResult+'<a href=\'javascript:minimize("vsr_'+vsrData.id+'");\' class="votemin">&mdash;</a>'+
			' <a href=\'javascript:close("vsr_'+vsrData.id+'");\' class="voteclose">X</a> </p>'+
		'</h3>'+
	'</div>'+
	'<div class="voteCnt">'+
		'<div class="voteCntR">'+
			'<div class="voteCntM">';
	for(var i in questions){
		var vsr = questions[i];
		if(vsr.type==="single"||vsr.type==="multi"){
			sElem += createVoteResult(vsr);
		}else if(vsr.type==="text"){
			sElem += createSurveyResult(vsr);
		}else{
			error("[ipad-live.vote][popupVoteAndSurveyResult] type of result is error:", vsr.type);
		}
	}
	
	sElem += 		'</div>'
				+'</div>'
			+'</div>'
			+'<div class="voteBtm">'
				+'<div class="voteBtmR">'
				+'<p class="voteBtmM"></p>'
				+'</div>'
			+'</div>';
	$(sElem).appendTo("#voteContainer");
	$("#vsr_"+ vsrData.id).bind("click",function(){focus("vsr_"+ vsrData.id);});
	focus("vsr_"+ vsrData.id);
}

function createVoteResult(voteResultData){
	var sVoteR = '<div class="toupiao">'+
				'<h3>'+voteResultData.subject+'</h3>'+
				'<div class="toupiaoCnt">';
	var vateTotal = voteResultData.total;
	for(var i in voteResultData.items){
		var item = voteResultData.items[i];
		var itmeTotal = item.total;
		sVoteR +='<li>'+
					'<table cellspacing="0" cellpadding="0" border="0" bgcolor="#ffffff" width="140" style="float:left;border:1px solid #366d00;"><tbody>'+
					'<tr>'+
						'<td width="'+calcRate(itmeTotal, vateTotal)+'%" height="8" style="background:url('+staticPrefix+'/static/ipad/images/progress-bar.gif) #5cbb00"></td>'+
						'<td width="100%"></td>'+
					'</tr>'+
				'</tbody></table>'+
				'<span class="floatl"><span style="display:inline-block;width:70px;">'+calcRate(itmeTotal, vateTotal)+' ('+calcRate(itmeTotal, vateTotal)+'%)</span><strong>'+item.content+'</strong></span>'+
				'</li>';
	}
	sVoteR +='</div>'
		+'</div>';
	return sVoteR;
}

function patchNbsp(value){
	
}

function calcRate(v, total){
	if(isNaN(v)||Number(v)==0)return "0";
	if(isNaN(total) || Number(total)==0)return "0";
	return Math.round(Number(v)*100/Number(total));
}

function createSurveyResult(surveyResultData){
	var sSurveyR = '<div class="diaocha">'+
						'<h3>'+surveyResultData.subject+'</h3>'+
						'<div class="diaochaCnt">'+
						'</div>'+
					'</div>';
	return sSurveyR;
}

function appendMinimizeItem(data){
	var eId;
	if(isQuestion(data)){
		eId = "vs_"+data.id;
	}else{
		eId = "vsr_"+data.id;
	}
	if(eId.length < 4){
		error("content error (expect {id:-, subject:-}):", data);
		return;
	}
	var eItem = createMinimizeItem(eId, data.subject);
	$("#minItemContainer ul").find(".current").removeClass("current");
	$("#minItemContainer ul").prepend(eItem);
	
	if(!isQuestion(data)){
		$(eItem).addClass("green");
	}
	
	debug("----------", eItem);
	$(eItem).bind("click", function(event){
		var _eItem = event.target;
		var eId = $(_eItem).attr("name");
		show(eId);
	});
}

function isQuestion(voteAndSurvey){
	if(voteAndSurvey.rootType ==="vote" || voteAndSurvey.rootType ==="survey"){
		return true;
	}else{
		return false;
	}
	
}

function createMinimizeItem(eId, subject){
	var sItem = '<li class="winItem current" name="'+eId+'">'+subject+'</li>';
	return $(sItem)[0];
}

function focus(eId){
	$("#"+eId).css("z-index",VS_ATTR.zIndex++);
	var item = $("#minItemContainer ul").find("li[name='"+eId+"']");
	item.addClass("current");
	item.siblings().removeClass("current");
}

function minimize(id){
	$("#"+id).hide();
}

function show(eId){
	$("#"+eId).show();
	focus(eId);
}

function close(eId){
	$("#"+eId).remove();
	var idx = eId.indexOf("_");
	var oId = eId.substr(idx+1);
	delete VoteSurvey[oId];
	$("#minItemContainer ul").find("li[name='"+eId+"']").remove();
	
	if($("#minItemContainer ul li").length==0){
		$("#minItemContainer").hide();
	}
}

